<template>
  <div>
    <el-row type="flex" justify="center">
      <el-col :span="12">
        <el-table :data="goods_list">
          <el-table-column label="商品名" prop="name"></el-table-column>
          <el-table-column label="价格" prop="price"></el-table-column>
          <el-table-column label="库存" prop="store"></el-table-column>
          <el-table-column label="">
              <template slot-scope="scope">
                  <el-button type="danger" @click="buy(scope.row)">购买</el-button>
              </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  data() {
    return {
      goods_list: []
    };
  },
  created() {
    this.axios
      .get("/goods")
      .then(resp => {
        console.log(resp.data);
        this.goods_list = resp.data;
      })
      .catch(error => {
        console.log(resp.data);
      });
  },
  methods:{
      buy(item){

        console.log(item)
          
        if(!sessionStorage.getItem("username")){
            //没有登录 去登录
            this.$router.push({"path":"/login2","query":{"callback":this.$route.fullPath}})
        }else{
            //登录成功，就添加购物车
           const uid=sessionStorage.getItem("uid")
            //先从localStorage中先读取 已经存放的购物记录

            const cart_str=localStorage.getItem(uid)  //获取的是字符串

            let cart_list=[]
            if(cart_str){
              //有存在的购物记录
               //把购物车记录 字符串 转成JSON对象
               cart_list=JSON.parse(cart_str)
            }
           
            //然后把新的购物记录 添加到 购物车记录列表中
            cart_list.push({"id":item.id,"name":item.name,"price":item.price,"num":1})

            //在把JSON对象 转成json字符串 在写入到 localStorage中

            const cart_list_str=JSON.stringify(cart_list)

            //根据用户id作为key，存放 该用户的购物记录
            localStorage.setItem(uid,cart_list_str)
        }
      }
  }
};
</script>

<style>
</style>